iT邦幫忙

2021 iThome 鐵人賽

DAY 17
0
Software Development

PHP 語法通關系列 第 17

Day17 PHP的常用函數-2:數組

  • 分享至 

  • xImage
  •  

數組

  • array(): 生成一個數組
  • range(): 創建並返回一個包含指定範圍的元素的數組
  • compact(): 創建一個由參數所帶變量組成的數組
<?php
$first = "Winnie";
$second = "is";
$third = " a bear";
$result = compact("first", "second",  "third");
print_r($result);

  • array_chunk(): 把一個數組分割為新的數組塊
  • array_merge(): 把兩個或多個數組合併為一個數組
  • array_slice(): 在數組中根據條件取出一段值,並返回
<?php
//array_chunk()
$arr = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
print_r(array_chunk($arr, 2));
echo '<hr>';

//array_merge()
$arr1 = array("a" => "apple", "b" => "bear");
$arr2 = array("c" => "cat", "b" => "bear");
print_r(array_merge($arr1, $arr2));
echo '<hr>';

//array_slice()
$arr = array(0 => "Dog", 1 => "Cat", 2 => "bear", 3 => "fish");
print_r(array_slice($arr, 1, 2));

  • array_sum(): 返回數組中所有值的總和
$arr = array(0 => "5", 1 => "150", 2 => "75");
echo array_sum($arr);//230
  • array_shift(): 刪除數組中的第一個元素,並返回被刪除元素的值
  • array_unshift(): 在數組開頭插入一個或多個元素
  • array_push(): 向數組最後壓入一個或多個元素
  • array_pop(): 取得(刪除)數組中的最後一個元素
<?php
//array_shift()
$arr = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
echo array_shift($arr);
print_r($arr);
echo '<hr>';

//array_unshift()
$arr1 = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
array_unshift($arr1, "Winnie");
print_r($arr1);
echo '<hr>';

//array_push()
$arr2 = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
array_push($arr2, "Winnie", "Cow");
print_r($arr2);
echo '<hr>';

//array_pop()
$arr3 = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
array_pop($arr3);
print_r($arr3);

  • shuffle(): 將數組打亂
  • count(): 計算數組中的單元數目或對像中的屬性個數
  • array_rand(): 從數組中隨機抽取一個或多個元素,注意是鍵名!!!
<?php
//shuffle()
$arr = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
shuffle($arr);
print_r($arr);
echo '<hr>';

//count()
$arr1 = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
$result = count($arr1);
echo $result;
echo '<hr>';

//array_rand()
$arr2 = array("a" => "apple", "b" => "bear", "c" => "cat", "d" => "duck");
$result = array_rand($arr2);
echo $result;


上一篇
Day16 PHP的常用函數-1:數學、字符串函數
下一篇
Day18 PHP的常用函數3:時間函數
系列文
PHP 語法通關30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言